package cn.itsource;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;

import java.util.HashMap;

public class EsTest {



    //新增
    @Test
    public void testAdd() throws Exception{
        //1.获取ES链接
        TransportClient client = ESClientUtil.getClient();
        // 2.准备要放入到ES中的数据
        HashMap<String , Object> map = new HashMap<>();
        map.put("id","1");
        map.put("name","柯基");
        map.put("age","2");
        map.put("sex","1");
        // 3.使用链式编程，将数据存入到ES中
        IndexRequestBuilder builder = client.prepareIndex("pethome", "pet", "1").setSource(map);
        // 4.得到添加文档结果
        System.out.println(builder.get());
        //关闭连接
        client.close();
    }

    //查询
    @Test
    public void testGet() throws Exception{
        //获取ES链接
        TransportClient client = ESClientUtil.getClient();
        //获取指定文档
        GetResponse response = client.prepareGet("pethome", "pet", "1").get();
        System.out.println(response);
        System.out.println(response.getSource());
        //关闭链接
        client.close();
    }

    //修改
    @Test
    public void testUpdate() throws Exception{
        //获取ES链接
        TransportClient client = ESClientUtil.getClient();
        //准备修改的数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","金毛");
        //使用链式编程，将要修改的数据存入到ES中
        UpdateResponse response = client.prepareUpdate("pethome", "pet", "1").setDoc(map).get();
        //修改结果
        System.out.println(response);
        //关闭链接
        client.close();
    }

    //删除
    @Test
    public void testDelete() throws Exception{
        //获取ES链接
        TransportClient client = ESClientUtil.getClient();
        //使用链式编程，删除指定文档
        DeleteResponse response = client.prepareDelete("pethome", "pet", "1").get();
        //删除结果
        System.out.println(response);
        //关闭链接
        client.close();
    }

    /**
     * @Description: 批量添加数据
     * @Author: Director
     * @return: void
     **/
    @Test
    public void testBatch() throws Exception {
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2.创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        // 3.批量创建文档，放入批量操作对象中
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学习Java!" + i)
                            .field("age", i - 1)
                            .field("sex", i%2)
                            .endObject()
            );
            BulkResponse result = bulk.add(builder).get();
            System.out.println(result.status());
        }
        // 4.关闭连接
        client.close();
    }

    //复杂查询
    @Test
    public void testComplex() throws Exception{
        //获取ES链接
        TransportClient client = ESClientUtil.getClient();
        // 查询条件：- 查询用户表，name包含：我在源码，age在1~12之间，每页大小2，从二页开始查，按照age倒序
        //获取查询对象
        SearchRequestBuilder builder = client.prepareSearch("pethome");
        //指定要搜索的类型
        builder.setTypes("user");
        //指定Query搜索对象，当参数是接口时我们可以传递：接口的工具类、接口实现、匿名内部类，此处传递接口工具类
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //指定DLS查询，name包含‘我在源码’
        boolQuery.must(QueryBuilders.matchQuery("name","我在源码"));
        //指定DLS过滤，age在1~12之间
        boolQuery.filter(QueryBuilders.rangeQuery("age").gte(1).lte(12)).filter(QueryBuilders.termQuery("sex",1));
        //讲搜索条件放入搜索对象中
        builder.setQuery(boolQuery);
        //设置分页起始位置
        builder.setFrom(2);
        //设置每页显示条数
        builder.setSize(2);
        //设置排序，按age倒序
        builder.addSort("age", SortOrder.DESC);
        //打印结果
        SearchHits hits = builder.get().getHits();
        System.out.println(hits.getTotalHits());
        //遍历结果
        for (SearchHit document : hits) {
            //getSourceAsMap-获取Source并转换为map
            System.out.println(document.getSourceAsMap());
        }
    }
}
